﻿
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

using Microsoft.AspNetCore.Mvc;
using UtilsORM.MySqlData;
using Models.JsonResultModel;
using Models.WebAdmin;
using ServiceWeb.DBGateway;
using ServiceWeb.DBBase;
using UtilsBase;
using UtilsORM;
using UtilsORM.MySqlData;
using GatewayServer.Common;

namespace GatewayServer.Controllers
{
    public class MagerSystemRoleController : BaseMagerFilterController
    {
        // GET: Mager_PropertyType
        public ActionResult List(IFormCollection FC, string Title = "", int PageIndex = 1, int PageSize = 15)
        {
            List<SugarParameter> sugarParameters = new List<SugarParameter>();

            string sqlwhere = " ";
            if (FC["txt_Search_Name"].ToString() != null && !string.IsNullOrEmpty(FC["txt_Search_Name"]))
            {
                sqlwhere = sqlwhere + " and r_name like '%" + FC["txt_Search_Name"].ToString().Trim() + "%' ";
                ViewBag.Search_Name = FC["txt_Search_Name"].ToString().Trim();
            }
            int totalRecord = 0;
            if (!string.IsNullOrEmpty(FC["hid_pageIndex"]))
            {
                PageIndex = int.Parse(FC["hid_pageIndex"].ToString());
            }
            string sql = "select * from bs_manage_role where 1= 1  " + sqlwhere;
            DataTable dt = MySqlYihongIot.getPageDataTable(PageIndex, PageSize, sql, sugarParameters, "r_code desc", ref totalRecord);


            // DataTable dt = new DBUtility.DataBase().QueryDtPageList(" bs_manage_role  ", " * ", sqlwhere, "r_code desc", PageSize, PageIndex, out totalRecord);
            ViewData["DataList"] = dt;

            ViewBag.PageSize = PageSize;
            ViewBag.RecordCount = totalRecord;//总条数
            ViewBag.PageCount = totalRecord % PageSize == 0 ? totalRecord / PageSize : totalRecord / PageSize + 1;//分的页数
            ViewBag.PageIndex = PageIndex;//当前页码
            return View();
        }
        public ActionResult ListDialog()
        {
            ViewBag.NewGuid = Guid.NewGuid();
            return View();
        }

        [HttpPost]
        public RespResultData Save(IFormCollection FC)
        {
            #region      

            string Name = FC["txt_Name"].ToString().Trim();
            string Remark = FC["txt_Remark"].ToString().Trim();
            int PtyS_order = int.Parse(FC["txt_Order"].ToString().Trim());
            string MenuGuid = FC["hid_MenuGuid"];
            string actionorder = Request.Query["actionorder"];
            string editguid = string.IsNullOrEmpty(FC["hid_edit_guid"].ToString().Trim()) ? Guid.NewGuid().ToString() : FC["hid_edit_guid"].ToString().Trim();//如果是有值，则是编辑保存,如果没有值则添加


            //判断是否重复
            //bs_manage_role getModel = new MySqlYihongIot().Db.Queryable<bs_manage_role>().Where(c => c.r_name == Name && c.r_guid != editguid).First();
            //if (getModel != null)
            //{
            //    //如果已经存在相同的数据

            //    return RespResult.Faild();
            //}
            bs_manage_role model = new bs_manage_role();
            model.r_guid = editguid;
            model.r_remark = Remark;
            model.r_name = Name;
            model.r_code = model.r_order = PtyS_order;
            model.r_status = 1;
            model.r_default_menu_guid = "00000000-0000-0000-0000-000000000000";
            model.r_c_guid = LoginUserInfo.userCompanyGuid.ToString();
            //--------添加到菜单权限表
            bs_manage_role_menu rmpmodel = new bs_manage_role_menu();

            List<bs_manage_role_menu> rmpList = new List<bs_manage_role_menu>();
            for (int i = 0; i < MenuGuid.Split(',').Length; i++)
            {
                if (!string.IsNullOrEmpty(MenuGuid.Split(',')[i]))
                {
                    rmpmodel = new bs_manage_role_menu();
                    rmpmodel.rm_guid = Guid.NewGuid().ToString();
                    rmpmodel.rm_menu_guid = MenuGuid.Split(',')[i];
                    rmpmodel.rm_r_guid = model.r_guid;
                    rmpmodel.rm_add_time = DateTime.Now;
                    rmpList.Add(rmpmodel);
                }
            }


            //添加
            if (actionorder == "add")
            {
                if (new DBBsClientRole().Add(model, rmpList) == true)
                {
                    return RespResult.Sucess();
                }

            }
            else if (actionorder == "upd")
            {
                //修改
                if (new DBBsClientRole().Edit(model, rmpList) == true)
                {
                    return RespResult.Sucess();
                }

            }

            return RespResult.Faild();
            #endregion
        }


        [HttpPost]
        public RespResultData Del(IFormCollection FC)
        {
            if (FC.Count > 0)
            {
                bs_manage_role getModel;
                List<bs_manage_role> List = new List<bs_manage_role>();

                List<string> str_param = Request.Form.Keys.ToList();
                for (int i = 0; i < str_param.Count; i++)
                {
                    if (str_param[i].ToLower().Contains("checkbox") && !string.IsNullOrEmpty(Request.Form[str_param[i]]))
                    {
                        string[] cbparam = Request.Form[str_param[i].ToString()].ToString().Split(',');
                        foreach (string pnum in cbparam)
                        {
                            getModel = new bs_manage_role();
                            getModel.r_guid = pnum;

                            List.Add(getModel);

                            // new WebXunCha.Common.Log().WriteLog(base.LoginUserInfo.Com_Name, base.LoginUserInfo.Project_Name, base.LoginUserInfo.Dep_Name, base.LoginUserInfo.Emp_Guid.ToString(), base.LoginUserInfo.Emp_Name.ToString(), " 删除角色 " + getModel.r_guid, 1);


                        }
                    }
                }

                if (List.Count > 0)
                {
                    if (new DBBsClientRole().Del(List) == true)
                    {
                        return RespResult.Sucess();
                    }

                }
            }
            return RespResult.Faild();
        }


        public RespResultData GetRole(string editguid)
        {
            string _rguid = editguid;
            bs_manage_role model = new MySqlYihongIot().Db.Queryable<bs_manage_role>().Where(c => c.r_guid == _rguid).First();

            //查询所有权限出来
            return RespResult.Sucess(model);

        }


        public RespResultData GetRoleMenuGuidList(string editguid)
        {
            string _rguid = editguid;
            //查询所有权限出来

            List<bs_manage_role_menu> menulist = new MySqlYihongIot().Db.Queryable<bs_manage_role_menu>().Where(c => c.rm_r_guid == _rguid).ToList();

            string rmpguid = "";
            foreach (bs_manage_role_menu menu in menulist)
            {
                if (rmpguid != "")
                {
                    rmpguid = rmpguid + ",";
                }
                rmpguid = rmpguid + menu.rm_menu_guid;
            }
            return RespResult.Sucess(rmpguid);

        }


        //[HttpPost]
        //public string GetRoleMsg(string roleguid)
        //{

        //    bs_manage_role model = new MySqlHelper().Db.Queryable<bs_manage_role>().Where(c => c.r_guid == roleguid).Select(c => c).First();
        //    if (model != null)
        //    {
        //        //查询所有权限出来
        //        return re
        //        return "[{\"respCode\":\"" + CommonModel.Model.ResponseCode.SUCCESS + "\",\"respMsg\":\"" + CommonModel.Model.ResponseCode.SUCCESS_MSG + "\",\"msg\":\"" + model.R_Remark + "\"}]";
        //    }
        //    else
        //    {
        //        return "[{\"respCode\":\"" + CommonModel.Model.ResponseCode.NOT_DATA_ERROR + "\",\"respMsg\":\"" + CommonModel.Model.ResponseCode.NOT_DATA_ERROR_MSG + "\"}]";
        //    }

        //}

        //[HttpPost]
        //public string GetRoleListByCode()
        //{
        //    #region
        //    string returnjson = "";
        //    int code = 0;
        //    string sql = "select max(r_code) from bs_manage_role inner join Q_Employee_Role on EmpR_R_Guid=r_guid and EmpR_Emp_Guid='" + base.LoginUserInfo.Emp_Guid + "' ";
        //    DataTable dt = new DataBase().QueryDt(sql);
        //    if (dt.Rows.Count > 0)
        //    {
        //        code = int.Parse(dt.Rows[0][0].ToString());
        //    }
        //    dt.Dispose();
        //    //判断是否职能

        //    List<DataModels.bs_manage_role> list = new Service.BLLQ_Employee_Role().GetRoleListByCode(code);
        //    for (int i = 0; i < list.Count; i++)
        //    {
        //        if (string.IsNullOrEmpty(returnjson))
        //        {
        //            returnjson = "{\"guid\":\"" + list[i].r_guid.ToString().ToLower() + "\",\"name\":\"" + list[i].r_name + "\",\"select\":\"-1\"}";
        //        }
        //        else
        //        {
        //            returnjson = returnjson + "," + "{\"guid\":\"" + list[i].r_guid.ToString().ToLower() + "\",\"name\":\"" + list[i].r_name + "\",\"select\":\"-1\"}";
        //        }
        //    }
        //    returnjson = "[" + returnjson + "]";

        //    return returnjson;
        //    #endregion
        //}

        //[HttpPost]
        //public string GetRoleListByCode_AllList()
        //{
        //    #region

        //    string returnjson = "";
        //    //判断是否职能

        //    List<bs_manage_role> list = new MySqlHelper().Db.Queryable<bs_manage_role>().Where(c => c.R_CPY_Guid == LoginUserInfo.userCompanyGuid.ToString()).OrderBy(c => c.R_Order).ToList();
        //    for (int i = 0; i < list.Count; i++)
        //    {
        //        if (string.IsNullOrEmpty(returnjson))
        //        {
        //            returnjson = "{\"guid\":\"" + list[i].r_guid.ToString().ToLower() + "\",\"name\":\"" + list[i].r_name + "\",\"select\":\"-1\"}";
        //        }
        //        else
        //        {
        //            returnjson = returnjson + "," + "{\"guid\":\"" + list[i].r_guid.ToString().ToLower() + "\",\"name\":\"" + list[i].r_name + "\",\"select\":\"-1\"}";
        //        }
        //    }
        //    returnjson = "[" + returnjson + "]";

        //    return returnjson;
        //    #endregion
        //}


        public ActionResult setMenu()
        {
            return View();
        }

        [HttpPost]
        public string ListZTreeData(string id = "", string rguid = "")
        {
            List<bs_manage_system_menu> list = new List<bs_manage_system_menu>();
            ZtreeItemModel ZI = new ZtreeItemModel();
            List<ZtreeItemModel> ZIList = new List<ZtreeItemModel>();
            if (string.IsNullOrEmpty(rguid)) rguid = Guid.NewGuid().ToString();
            string _rguid = rguid;
            if (!string.IsNullOrEmpty(rguid))
            {

                List<bs_manage_role_menu> rmplist = new MySqlYihongIot().Db.Queryable<bs_manage_role_menu>().Where(c => c.rm_r_guid == _rguid).ToList();
                list = new MySqlYihongIot().Db.Queryable<bs_manage_system_menu>().Where(c => c.menu_status == 0).OrderBy(c => c.menu_order).ToList();
                for (int i = 0; i < list.Count; i++)
                {

                    if (list.Where(c => c.menu_guid == list[i].menu_parent).Count() < 1 && list[i].menu_guid != list[i].menu_parent)
                    {
                        continue;
                    }


                    ZI = new ZtreeItemModel();
                    ZI.id = list[i].menu_guid.ToString().ToLower();
                    ZI.pId = list[i].menu_parent.ToString().ToLower();
                    ZI.name = list[i].menu_name;
                    ZI.open = "true";
                    ZI.isParent = "false";
                    if (list.Where(c => c.menu_parent == list[i].menu_guid).Count() > 0)
                    {
                        ZI.isParent = "true";
                    }

                    if (rmplist.Where(c => c.rm_menu_guid == list[i].menu_guid).Count() > 0)
                    {
                        ZI.@checked = true;
                        ZI.chkDisabled = false;
                    }
                    else
                    {

                        ZI.@checked = false;
                        ZI.chkDisabled = false;

                    }
                    ZIList.Add(ZI);
                }


            }


            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            string result = JsonConvert.SerializeObject(ZIList, Formatting.Indented, settings);//需要注意的是，如果返回的是一个集合，那么还要在它的上面再封装一个类。否则客户端收到会出错的。
            return result.Replace("@", "");
        }

    }
}